package cz.cvut.testRMI;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class Server implements Common {

    public Server() {
        super();
    }

    public int secti(int a, int b) throws RemoteException {
        return a+b;
    }
    
    public Container changeDetails(Container person) throws RemoteException {
    	person.change();
    	System.out.println(person);
    	return person;
    }
    
    public void end()  throws RemoteException {
    	Registry registry = LocateRegistry.getRegistry();
    	try {
    		registry.unbind("MujServer");
    		UnicastRemoteObject.unexportObject(this, true);
    		System.out.println("RMI odpojeno");
    	} catch (NotBoundException e) {
    		System.out.println(e);
    	}
    }
    
    public void pockej() throws RemoteException {
    	Object o = new Object();
    	try {
	    	synchronized (o) {
	    		System.err.println("Zacal cekat");
	    		o.wait(3000);
	    		System.err.println("Docekal.");
	    	}
	    } catch (Exception e) {
	    	System.err.println("Vysralo se to exception:");
            e.printStackTrace();
	    }
    }

    public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
        try {
            String name = "MujServer";
            Server server = new Server();
            Common stub = (Common) UnicastRemoteObject.exportObject(server, 0);
            Registry registry = LocateRegistry.getRegistry();
            registry.rebind(name, stub);
            System.out.println("RMI registrovano");
            
            Object o = new Object();
            
            for (int i=0; i<15; i++) {
            	synchronized (o) {
            		o.wait(1000);
            	}
            	System.out.println((i+1) + ". sekunda odbita");
            }
            System.out.println("Main konci");
        } catch (Exception e) {
            System.err.println("Vysralo se to exception:");
            e.printStackTrace();
        }
    }
}
